#include <STC89C5xRC.H>

sbit OneWire_DQ=P3^7;
unsigned char i=0;

unsigned char OneWire_Init()
{	
	unsigned char i=0;
	unsigned char AckBit;
	EA=0;
	OneWire_DQ=1;
	OneWire_DQ=0;
	i = 227;while (--i); //500us
	OneWire_DQ=1;
	i = 29;while (--i); //70us
	AckBit=OneWire_DQ;
	i = 227;while (--i); //500us
	EA=1;
	return AckBit;
}

//发送一位
void OneWire_SendBit(unsigned char Bit)
{	
	unsigned char i=0;
	EA=0;
	OneWire_DQ=0;
	i = 4;while (--i); //10us
	OneWire_DQ=Bit;
	i = 22;while (--i); //49us
	OneWire_DQ=1;
	EA=1;
}

//接收一位
unsigned char OneWire_ReceiveBit()
{	
	unsigned char i=0;
	unsigned char Bit;
	EA=0;
	OneWire_DQ=0;
	i = 2;while (--i); //5us
	OneWire_DQ=1;
	i = 2;while (--i); //5us
	Bit=OneWire_DQ;
	i = 23;while (--i); //51us
	EA=1;
	return Bit;
}

//发送一个字节
void OneWire_SendByte(unsigned char Byte)
{
	unsigned char i=0;
	for(i=0;i<8;i++)
	{
		OneWire_SendBit(Byte&(0x01<<i));
	}
}

//接受一个字节
unsigned char OneWire_ReceiveByte()
{
	unsigned char Byte=0;
	unsigned char i=0;
	for(i=0;i<8;i++)
	{
		Byte|=(OneWire_ReceiveBit()<<i);
		//if(OneWire_ReceiveBit){Byte|=(0x01<<i);}
	}
	return Byte;
}
